using System.Text;
using Newtonsoft.Json;

namespace SPI.AgentServer.Services.AI;

/// <summary>
/// 提示词管理器 - 管理与 AI 模型交互的所有提示词
/// 负责：
/// 1. 生成系统提示词（System Prompt）
/// 2. 构建查询提示词
/// 3. 管理工具定义
/// 4. 处理错误修正提示词
/// </summary>
public class PromptManager : IPromptManager
{
    private readonly ILogger<PromptManager> _logger;
    // 缓存数据库结构描述
    private static string? _cachedSchemaDescription;
    private static DateTime _cacheTime;
    private static readonly TimeSpan CacheDuration = TimeSpan.FromHours(1); // 缓存1小时

    public PromptManager(ILogger<PromptManager> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 获取系统提示词
    /// 这是给 AI 模型的基础指令，定义了它的角色和行为规范
    /// </summary>
    /// <returns>系统提示词字符串</returns>
    /// <summary>
    /// 设置缓存的数据库结构描述
    /// </summary>
    public void SetSchemaDescription(string description)
    {
        _cachedSchemaDescription = description;
        _cacheTime = DateTime.Now;
        _logger.LogInformation("数据库结构已缓存，大小：{Size} 字符", description.Length);
    }

    /// <summary>
    /// 获取缓存的数据库结构描述
    /// </summary>
    public string? GetCachedSchemaDescription()
    {
        if (_cachedSchemaDescription == null)
            return null;
            
        // 检查缓存是否过期
        if (DateTime.Now - _cacheTime > CacheDuration)
        {
            _logger.LogWarning("数据库结构缓存已过期");
            return null;
        }
        
        return _cachedSchemaDescription;
    }

    public string GetSystemPrompt()
    {
        var currentYear = DateTime.Now.Year;
        return $@"You are a database query assistant. Your job is to select the most appropriate tool for user questions.

IMPORTANT Rules:
1. ALWAYS check if there is a specific business tool (like get_visitor_vehicles, get_device_stats, get_library_access) before using execute_sql
2. Business tools are better than execute_sql because they use pre-validated queries
3. NEVER use execute_sql if a business tool exists for the query type
4. For dormitory/library access queries, ALWAYS use get_library_access tool
5. For vehicle queries, ALWAYS use get_oncampus_visitor_vehicles or get_vehicle_management
6. Only use execute_sql if NO appropriate business tool exists
7. Only generate SELECT statements
8. Never generate UPDATE, DELETE, INSERT, DROP, CREATE, or ALTER statements
9. Return pure JSON format only
10. Current year is {currentYear}. When user mentions a month without year (like '九月份', '9月'), ALWAYS use {currentYear} as the year

Response format:
For business tools:
{{
    ""action"": {{
        ""tool"": ""tool_name"",
        ""parameters"": {{
            ""param1"": ""value1"",
            ""param2"": ""value2""
        }}
    }}
}}

For SQL queries (only if no business tool exists):
{{
    ""action"": {{
        ""tool"": ""execute_sql"",
        ""parameters"": {{
            ""sql"": ""SELECT statement"",
            ""databaseName"": ""database name""
        }}
    }}
}}

For table description:
{{
    ""action"": {{
        ""tool"": ""describe_table"",
        ""parameters"": {{
            ""tableName"": ""table name""
        }}
    }}
}}

For direct answers:
{{
    ""directAnswer"": ""answer content""
}}";
    }

    /// <summary>
    /// 构建查询提示词
    /// 将用户的自然语言查询、可用工具和上下文信息组合成完整的提示词
    /// </summary>
    /// <param name="userQuery">用户的自然语言查询</param>
    /// <param name="availableTools">可用的工具列表</param>
    /// <param name="context">额外的上下文信息（如数据库名称等）</param>
    /// <returns>构建好的完整提示词</returns>
    public string BuildQueryPrompt(string userQuery, List<ToolDefinition> availableTools, string? context = null)
    {
        var sb = new StringBuilder();
        
        // 添加系统提示词
        sb.AppendLine(GetSystemPrompt());
        sb.AppendLine();
        
        // 自动包含数据库结构描述（如果有缓存）
        var schemaDesc = GetCachedSchemaDescription();
        if (!string.IsNullOrEmpty(schemaDesc))
        {
            sb.AppendLine("当前数据库结构：");
            sb.AppendLine(schemaDesc);
            sb.AppendLine();
        }
        
        // 添加可用工具列表
        if (availableTools != null && availableTools.Any())
        {
            sb.AppendLine("Available Tools:");
            foreach (var tool in availableTools)
            {
                sb.AppendLine($"- {tool.Name}: {tool.Description}");
                if (tool.Parameters != null && tool.Parameters.Any())
                {
                    sb.AppendLine($"  Parameters: {string.Join(", ", tool.Parameters.Keys)}");
                }
            }
            sb.AppendLine();
        }

        // 添加示例
        sb.AppendLine("Examples:");
        sb.AppendLine();
        sb.AppendLine("Question: 查看现在所有在校的外来车辆");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_oncampus_visitor_vehicles"",""parameters"":{}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 查询10月在校的外来访客车辆");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_oncampus_visitor_vehicles"",""parameters"":{""month"":""2025-10""}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 显示一周内反复进出宿舍超过5次的学生");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_gate_records"",""parameters"":{""startTime"":""2025-01-14"",""endTime"":""2025-01-21"",""gateType"":2,""countOnly"":true}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 查询刘红磊最近的宿舍进出记录");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_gate_records"",""parameters"":{""studentName"":""刘红磊"",""gateType"":2}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 查询九月份 李思瑾的宿舍进出记录");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_gate_records"",""parameters"":{""studentName"":""李思瑾"",""startTime"":""2025-09"",""gateType"":2}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 哪些摄像头离线了？");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_device_status"",""parameters"":{""deviceType"":""摄像头"",""onlineStatus"":1}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 哪些摄像头在线？");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_device_status"",""parameters"":{""deviceType"":""摄像头"",""onlineStatus"":2}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 今天有多少设备报警？");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_alarm_stats"",""parameters"":{""summaryOnly"":true}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 故障最多的设备排名");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_device_alarm_ranking"",""parameters"":{""rankType"":""fault_count"",""topN"":10}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 昨晚10点后谁进了图书馆？");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_personnel_access"",""parameters"":{""startTime"":""2025-01-22 22:00:00"",""location"":""图书馆"",""direction"":1}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 今天进校了多少人？");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_campus_stats"",""parameters"":{""statsType"":""entry_count""}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 现在有哪些外来车辆在校？");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_vehicle_management"",""parameters"":{""queryType"":""on_campus""}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 今天有车辆超速吗？");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_vehicle_management"",""parameters"":{""queryType"":""speeding""}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 查看设备统计");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_device_stats"",""parameters"":{}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 查询十月份图书馆进出情况");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_library_access"",""parameters"":{""month"":""2025-10"",""gateType"":3}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 昨晚10点后谁进了图书馆？");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_library_access"",""parameters"":{""startTime"":""2025-10-27 22:00:00"",""gateType"":3}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 统计反复进出宿舍超过5次的学生");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_library_access"",""parameters"":{""gateType"":2,""aggregateStats"":true,""minCount"":5,""month"":""2025-10""}}}");
        sb.AppendLine();
        sb.AppendLine("Question: 显示一周内反复进出宿舍超过5次的学生");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""get_library_access"",""parameters"":{""gateType"":2,""aggregateStats"":true,""minCount"":5,""startTime"":""2025-10-21""}}}");
        sb.AppendLine();
        sb.AppendLine("Question: query all students");
        sb.AppendLine(@"Answer: {""action"":{""tool"":""execute_sql"",""parameters"":{""sql"":""SELECT * FROM students"",""databaseName"":""Test""}}}");
        sb.AppendLine();

        // 用户查询
        sb.AppendLine($"User question: {userQuery}");
        
        if (!string.IsNullOrEmpty(context))
        {
            sb.AppendLine($"上下文：{context}");
        }
        
        sb.AppendLine();
        sb.AppendLine("Generate JSON response based on user question:");

        return sb.ToString();
    }

    public string BuildErrorCorrectionPrompt(string originalQuery, string error, string? previousAttempt = null)
    {
        var sb = new StringBuilder();
        sb.AppendLine($"原始查询：{originalQuery}");
        sb.AppendLine($"错误信息：{error}");
        
        if (!string.IsNullOrEmpty(previousAttempt))
        {
            sb.AppendLine($"之前的尝试：{previousAttempt}");
        }

        sb.AppendLine("\n请根据错误信息修正查询。可能的原因：");
        sb.AppendLine("1. 表名或字段名错误");
        sb.AppendLine("2. SQL语法错误");
        sb.AppendLine("3. 权限不足");
        sb.AppendLine("4. 需要使用其他工具");
        sb.AppendLine("\n请提供修正后的方案。");

        return sb.ToString();
    }

    /// <summary>
    /// 获取可用的工具定义列表
    /// 这些工具定义会告诉 AI 模型有哪些工具可以使用，以及如何使用它们
    /// </summary>
    /// <returns>工具定义列表</returns>
    public List<ToolDefinition> GetAvailableTools()
    {
        return new List<ToolDefinition>
        {
            // 工具1：执行 SQL 查询
            new ToolDefinition
            {
                Name = "execute_sql",
                Description = "执行SQL查询语句（仅支持SELECT）",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["sql"] = new ParameterDefinition 
                    { 
                        Type = "string", 
                        Description = "要执行的SQL查询语句", 
                        Required = true 
                    },
                    ["database"] = new ParameterDefinition 
                    { 
                        Type = "string", 
                        Description = "数据库名称，默认使用主数据库", 
                        Required = false 
                    }
                }
            },
            new ToolDefinition
            {
                Name = "describe_table",
                Description = "获取表结构信息",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["tableName"] = new ParameterDefinition 
                    { 
                        Type = "string", 
                        Description = "表名", 
                        Required = true 
                    },
                    ["database"] = new ParameterDefinition 
                    { 
                        Type = "string", 
                        Description = "数据库名称", 
                        Required = false 
                    }
                }
            },
            new ToolDefinition
            {
                Name = "run_prebuilt_query",
                Description = "运行预定义的复杂查询（用于分区表、跨库查询等）",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["queryName"] = new ParameterDefinition 
                    { 
                        Type = "string", 
                        Description = "预定义查询名称", 
                        Required = true 
                    },
                    ["parameters"] = new ParameterDefinition 
                    { 
                        Type = "object", 
                        Description = "查询参数", 
                        Required = false 
                    }
                }
            },
            new ToolDefinition
            {
                Name = "get_time_range",
                Description = "获取时间范围（用于分区表查询）",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["description"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "时间描述，如'今天'、'本周'、'上个月'等",
                        Required = true
                    }
                }
            },
            // 业务工具
            new ToolDefinition
            {
                Name = "get_device_stats",
                Description = "获取设备统计信息，包括总数、在线数、离线数、异常数等",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["deviceType"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "设备类型ID（可选）",
                        Required = false
                    },
                    ["areaId"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "区域ID（可选）",
                        Required = false
                    }
                }
            },
            new ToolDefinition
            {
                Name = "get_recent_alarms",
                Description = "查询最近的告警记录，支持按时间范围、告警级别、区域等条件筛选",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["limit"] = new ParameterDefinition
                    {
                        Type = "integer",
                        Description = "返回记录数量，默认10，最大1000",
                        Required = false
                    },
                    ["alarmLevel"] = new ParameterDefinition
                    {
                        Type = "integer",
                        Description = "告警级别",
                        Required = false
                    },
                    ["areaId"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "区域ID",
                        Required = false
                    },
                    ["startTime"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "开始时间（格式：yyyy-MM-dd HH:mm:ss）",
                        Required = false
                    },
                    ["endTime"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "结束时间（格式：yyyy-MM-dd HH:mm:ss）",
                        Required = false
                    },
                    ["operateStatus"] = new ParameterDefinition
                    {
                        Type = "integer",
                        Description = "处理状态",
                        Required = false
                    }
                }
            },
            new ToolDefinition
            {
                Name = "get_area_stats",
                Description = "获取区域统计信息，包括区域总数、设备数量、告警数量等",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["areaId"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "区域ID（可选，为空则返回所有区域）",
                        Required = false
                    },
                    ["includeChildren"] = new ParameterDefinition
                    {
                        Type = "boolean",
                        Description = "是否包含子区域",
                        Required = false
                    }
                }
            },
            new ToolDefinition
            {
                Name = "get_user_stats",
                Description = "获取用户统计信息，包括总用户数、在线用户数、按性别统计等",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["includeDetails"] = new ParameterDefinition
                    {
                        Type = "boolean",
                        Description = "是否返回详细用户列表，默认false返回统计摘要",
                        Required = false
                    }
                }
            },
            new ToolDefinition
            {
                Name = "get_database_schema",
                Description = "查询数据库表结构信息，包括表名、列名、数据类型等。用于了解数据库中有哪些表和字段。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["table_name_pattern"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "表名筛选模式（可选），如'tbl'、'device'、'user'等，用于过滤特定的表",
                        Required = false
                    }
                }
            },
            new ToolDefinition
            {
                Name = "get_visitor_vehicles",
                Description = "查询当前在校的外来访客车辆信息（基于TblMotorVehicleManagement表），包括车牌号、车主、入校时间、在校时长等。用于回答'有哪些外来车辆在校'、'查看访客车辆'等问题。支持按时间范围筛选。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["startTime"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "开始时间（可选），格式：'YYYY-MM-DD HH:mm:ss'，如 '2025-01-14 00:00:00'",
                        Required = false
                    },
                    ["endTime"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "结束时间（可选），格式：'YYYY-MM-DD HH:mm:ss'，如 '2025-01-15 00:00:00'",
                        Required = false
                    }
                }
            },
            new ToolDefinition
            {
                Name = "get_oncampus_visitor_vehicles",
                Description = "【推荐】查询当前在校的外来访客车辆详细信息（基于停车订单分表tblparkinginorder），包括车牌号、进入时间、停留时长、车辆照片等。支持按月份查询。用于回答'查看现在所有在校的外来车辆'、'有哪些访客车辆还没离开'等问题。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["month"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "查询的月份（可选），格式：'yyyy-MM' 或完整日期，如 '2025-10'。默认当前月份",
                        Required = false
                    }
                }
            },
            new ToolDefinition
            {
                Name = "get_gate_records",
                Description = "查询学生进出闸机记录（宿舍、图书馆、校门等），支持按学生姓名、时间范围筛选，可统计进出次数。用于回答'查看闸机记录'、'统计进出次数'、'反复进出宿舍的学生'等问题。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["studentName"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "学生姓名（可选），如'刘红磊'",
                        Required = false
                    },
                    ["startTime"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "开始时间（可选），格式：'YYYY-MM-DD'或'YYYY-MM-DD HH:mm:ss'。如果用户只说月份（如'九月份'、'9月'），请使用当前年份2025，格式为'2025-09'",
                        Required = false
                    },
                    ["endTime"] = new ParameterDefinition
                    {
                        Type = "string",
                        Description = "结束时间（可选），格式：'YYYY-MM-DD'或'YYYY-MM-DD HH:mm:ss'。如果用户只说月份（如'九月份'、'9月'），请使用当前年份2025，格式为'2025-09'",
                        Required = false
                    },
                    ["gateType"] = new ParameterDefinition
                    {
                        Type = "integer",
                        Description = "闸机类型（可选）：1-校门口，2-学生公寓/宿舍，3-图书馆，4-办公区。默认2（学生公寓）",
                        Required = false
                    },
                    ["countOnly"] = new ParameterDefinition
                    {
                        Type = "boolean",
                        Description = "是否只统计次数（可选）：true-只返回统计信息，false-返回详细记录。默认false",
                        Required = false
                    }
                }
            },

            // 设备状态查询工具
            new ToolDefinition
            {
                Name = "get_device_status",
                Description = "查询设备在线状态和故障信息，支持按设备类型、区域、在线状态筛选。用于回答'哪些设备离线'、'设备故障列表'、'某区域设备状态'等问题。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["deviceType"] = new ParameterDefinition { Type = "string", Description = "设备类型关键词（可选），如'摄像头'、'闸机'、'NVR'", Required = false },
                    ["areaName"] = new ParameterDefinition { Type = "string", Description = "区域名称（可选），如'图书馆'、'3号楼'", Required = false },
                    ["onlineStatus"] = new ParameterDefinition { Type = "integer", Description = "在线状态（可选）：1-离线，2-在线", Required = false },
                    ["onlyFaulty"] = new ParameterDefinition { Type = "boolean", Description = "是否只查询故障设备（可选）：true-只查故障，false-查全部。默认false", Required = false }
                }
            },

            // 报警统计查询工具
            new ToolDefinition
            {
                Name = "get_alarm_stats",
                Description = "查询设备报警统计信息，支持按时间范围、设备类型、处理状态筛选。用于回答'今天有多少报警'、'未处理的报警'、'某类型设备报警情况'等问题。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["startTime"] = new ParameterDefinition { Type = "string", Description = "开始时间（可选），格式YYYY-MM-DD。默认今天", Required = false },
                    ["endTime"] = new ParameterDefinition { Type = "string", Description = "结束时间（可选），格式YYYY-MM-DD", Required = false },
                    ["deviceType"] = new ParameterDefinition { Type = "string", Description = "设备类型关键词（可选）", Required = false },
                    ["operateStatus"] = new ParameterDefinition { Type = "integer", Description = "处理状态（可选）：1-待处理，2-处理中，3-已处理", Required = false },
                    ["summaryOnly"] = new ParameterDefinition { Type = "boolean", Description = "是否只返回汇总统计（可选）：true-只汇总，false-详细列表。默认false", Required = false }
                }
            },

            // 设备故障排名工具
            new ToolDefinition
            {
                Name = "get_device_alarm_ranking",
                Description = "查询设备故障排名信息，包括故障次数、离线时长等。用于回答'故障最多的设备'、'离线时长排名'、'最近离线过的设备'等问题。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["days"] = new ParameterDefinition { Type = "integer", Description = "统计最近多少天（可选），默认30天", Required = false },
                    ["topN"] = new ParameterDefinition { Type = "integer", Description = "返回前N名（可选），默认10", Required = false },
                    ["rankType"] = new ParameterDefinition { Type = "string", Description = "排名类型（可选）：fault_count-故障次数，offline_count-离线次数，offline_duration-离线时长。默认fault_count", Required = false },
                    ["deviceType"] = new ParameterDefinition { Type = "string", Description = "设备类型关键词（可选），如'摄像头'", Required = false }
                }
            },

            // 人员进出查询工具
            new ToolDefinition
            {
                Name = "get_personnel_access",
                Description = "查询人员通过闸机的进出记录，支持按姓名、学工号、时间范围、位置筛选。用于回答'谁进了某区域'、'某人的进出记录'、'深夜进出人员'等问题。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["personName"] = new ParameterDefinition { Type = "string", Description = "人员姓名（可选）", Required = false },
                    ["personId"] = new ParameterDefinition { Type = "string", Description = "学工号（可选）", Required = false },
                    ["startTime"] = new ParameterDefinition { Type = "string", Description = "开始时间（可选），格式YYYY-MM-DD HH:mm:ss", Required = false },
                    ["endTime"] = new ParameterDefinition { Type = "string", Description = "结束时间（可选），格式YYYY-MM-DD HH:mm:ss", Required = false },
                    ["location"] = new ParameterDefinition { Type = "string", Description = "位置关键词（可选），如'图书馆'、'教学楼'", Required = false },
                    ["direction"] = new ParameterDefinition { Type = "integer", Description = "进出方向（可选）：1-进，0-出", Required = false },
                    ["abnormalTime"] = new ParameterDefinition { Type = "boolean", Description = "是否查询异常时段（深夜22:00-06:00）（可选），默认false", Required = false }
                }
            },

            // 在校人数统计工具
            new ToolDefinition
            {
                Name = "get_campus_stats",
                Description = "统计在校人数相关信息，包括今天进校人数、当前在校人数、各部门统计等。用于回答'今天多少人进校'、'现在有多少人在校'、'各部门人数统计'等问题。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["statsType"] = new ParameterDefinition { Type = "string", Description = "统计类型（可选）：entry_count-进校人数，on_campus-在校人数，by_department-按部门统计。默认entry_count", Required = false },
                    ["queryDate"] = new ParameterDefinition { Type = "string", Description = "查询日期（可选），格式YYYY-MM-DD。默认今天", Required = false },
                    ["byDepartment"] = new ParameterDefinition { Type = "boolean", Description = "是否按部门统计（可选），默认false", Required = false }
                }
            },

            // 车辆管理查���工具
            new ToolDefinition
            {
                Name = "get_vehicle_management",
                Description = "查询车辆进出和管理信息，支持按车牌号、时间范围、车辆类型筛选。用于回答'外来车辆在校'、'车辆进出记录'、'超速车辆'、'长时间停留车辆'等问题。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["plateNumber"] = new ParameterDefinition { Type = "string", Description = "车牌号（可选）", Required = false },
                    ["startTime"] = new ParameterDefinition { Type = "string", Description = "开始时间（可选），格式YYYY-MM-DD", Required = false },
                    ["endTime"] = new ParameterDefinition { Type = "string", Description = "结束时间（可选），格式YYYY-MM-DD", Required = false },
                    ["queryType"] = new ParameterDefinition { Type = "string", Description = "查询类型（可选）：all-全部记录，on_campus-在校车辆，speeding-超速车辆，long_stay-长时间停留，night_entry-夜间进校，count-车辆数统计。默认all", Required = false },
                    ["stayDays"] = new ParameterDefinition { Type = "integer", Description = "停留天数（可选），用于long_stay类型，默认3天", Required = false }
                }
            },

            // 黑名单活动查询工具
            new ToolDefinition
            {
                Name = "get_blacklist_activity",
                Description = "查询黑名单人员的活动记录。用于回答'黑名单人员今天有刷卡吗'等问题。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["queryDate"] = new ParameterDefinition { Type = "string", Description = "查询日期（可选），格式YYYY-MM-DD。默认今天", Required = false },
                    ["personName"] = new ParameterDefinition { Type = "string", Description = "人员姓名（可选）", Required = false }
                }
            },

            // 部门员工查询工具
            new ToolDefinition
            {
                Name = "get_department_employee",
                Description = "查询部门员工信息和进出记录，支持跨月分表查询。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["department"] = new ParameterDefinition { Type = "string", Description = "部门名称（可选）", Required = false },
                    ["employeeName"] = new ParameterDefinition { Type = "string", Description = "员工姓名（可选）", Required = false },
                    ["queryDate"] = new ParameterDefinition { Type = "string", Description = "查询日期（可选），格式YYYY-MM-DD。默认今天", Required = false },
                    ["queryType"] = new ParameterDefinition { Type = "string", Description = "查询类型（可选）：access-进出记录，info-员工信息。默认access", Required = false },
                    ["months"] = new ParameterDefinition { Type = "integer", Description = "查询跨几个月（可选），默认1", Required = false }
                }
            },

            // 人员出入详情工具
            new ToolDefinition
            {
                Name = "get_personnel_inout_detail",
                Description = "查询人员在特定位置的进出详情（区别于闸机记录）。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["location"] = new ParameterDefinition { Type = "string", Description = "位置关键词（可选）", Required = false },
                    ["queryDate"] = new ParameterDefinition { Type = "string", Description = "查询日期（可选），格式YYYY-MM-DD。默认今天", Required = false },
                    ["inOutInfo"] = new ParameterDefinition { Type = "integer", Description = "进出标识（可选）：1-进入，0-离开", Required = false }
                }
            },

            // 车辆特殊信息查询工具
            new ToolDefinition
            {
                Name = "get_vehicle_special_info",
                Description = "查询车主信息、电动车记录、白名单车辆等。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["queryType"] = new ParameterDefinition { Type = "string", Description = "查询类型（可选）：owner-车主信息，electric-电动车记录，whitelist-白名单车辆。默认owner", Required = false },
                    ["ownerName"] = new ParameterDefinition { Type = "string", Description = "车主姓名（可选）", Required = false },
                    ["queryDate"] = new ParameterDefinition { Type = "string", Description = "查询日期（可选），格式YYYY-MM-DD。默认今天", Required = false }
                }
            },

            // 车辆统计工具
            new ToolDefinition
            {
                Name = "get_vehicle_stats",
                Description = "统计车辆进出数量，支持按日期分组。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["days"] = new ParameterDefinition { Type = "integer", Description = "统计最近多少天（可选），默认7天", Required = false },
                    ["startDate"] = new ParameterDefinition { Type = "string", Description = "开始日期（可选），格式YYYY-MM-DD", Required = false }
                }
            },

            // 门禁进出查询工具（图书馆、宿舍、校门等）
            new ToolDefinition
            {
                Name = "get_library_access",
                Description = "查询门禁进出记录（基于闸机分表tblgateinformation），支持图书馆、宿舍、校门等不同类型，支持聚合统计。用于回答'谁进了图书馆'、'反复进出宿舍的学生'、'图书馆进出次数统计'、'一周内进出宿舍超过5次的学生'等问题。",
                Parameters = new Dictionary<string, ParameterDefinition>
                {
                    ["gateType"] = new ParameterDefinition { Type = "integer", Description = "闸机类型（可选）：1=校门口，2=宿舍，3=图书馆，4=办公区。默认3（图书馆）", Required = false },
                    ["aggregateStats"] = new ParameterDefinition { Type = "boolean", Description = "是否聚合统计（可选）：true=按学生统计进出次数，false=返回详细记录。默认false", Required = false },
                    ["minCount"] = new ParameterDefinition { Type = "integer", Description = "最小次数阈值（可选），仅在aggregateStats=true时有效。用于筛选进出次数超过指定值的学生", Required = false },
                    ["month"] = new ParameterDefinition { Type = "string", Description = "查询月份（可选），格式yyyy-MM，如'2025-10'。默认当前月份", Required = false },
                    ["startTime"] = new ParameterDefinition { Type = "string", Description = "开始时间（可选），格式YYYY-MM-DD HH:mm:ss。如不指定则使用月份的第一天", Required = false },
                    ["endTime"] = new ParameterDefinition { Type = "string", Description = "结束时间（可选），格式YYYY-MM-DD HH:mm:ss。如不指定则使用月份的最后一天", Required = false },
                    ["studentId"] = new ParameterDefinition { Type = "string", Description = "学工号（可选）", Required = false },
                    ["studentName"] = new ParameterDefinition { Type = "string", Description = "学生姓名（可选）", Required = false }
                }
            }
        };
    }
}
